﻿using System;
using System.Collections.Generic;
using UnityEngine;
using Debug = System.Diagnostics.Debug;

namespace Core
{
    public class TableSystem : Component, IAwake
    {
        private readonly Dictionary<string, ITable> dict = new();

        public T GetSO<T>() where T : ScriptableObject, ITable
        {
            var type = typeof(T);
            var name = type.Name;
            if (dict.TryGetValue(name, out var value))
            {
                return value as T;
            }

            var asset = G.Res.LoadSync($"Res/Conf/Table/{name}.asset");
            var tbl = asset.Obj as T;
            //tbl.G = G;
            //tbl.Awake();
            dict[name] = tbl;
            return tbl;
        }

        public T GetJson<T>() where T : class, ITable
        {
            var type = typeof(T);
            var name = type.Name;
            if (dict.TryGetValue(name, out var value))
            {
                return value as T;
            }

            var key = name[..name.IndexOf("_", StringComparison.Ordinal)];
            var asset = G.Res.LoadSync($"Res/Conf/Json/{key}.json");
            var textAsset = asset.Obj as TextAsset;
            Debug.Assert(textAsset != null, nameof(textAsset) + " != null");
            var tbl = Utils.Json.Deserialize<T>(textAsset.text);
            dict[name] = tbl;
            return tbl;
        }

        public void Awake()
        {
            log.d("TableSystem.Awake");
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();

            log.d("TableSystem.Dispose");
        }
    }
}